<?php

include_once dirname(dirname(__FILE__)).'/nn_logic/nl_common.func.php';
include_once 'op_queue.const.php';
include_once dirname(dirname(__FILE__)).'/mgtv_v2/models/sp_model.php';
include_once dirname(dirname(__FILE__)).'/mgtv_v2/models/c2_task_model.php';
error_reporting(E_ALL ^ E_NOTICE);
class op_queue {
	private $debug_log;

	private $table='nns_mgtvbk_op_queue';

	private $weight_table='nns_mgtvbk_op_weight';

	private $log_table='nns_mgtvbk_op_log';

	private $fileds = array(
                'nns_id',
                'nns_message_id',
                'nns_from',
                'nns_ex_data',
                'nns_release_time',
                'nns_weight',
                'nns_org_id',
                'nns_video_id',
                'nns_type',
                'nns_action',
                'nns_status',
                'nns_name',
                'nns_media_id',
                'nns_index_id',
                'nns_op_mtime',
                'nns_is_group',
                'nns_cp_id',
            );

//	默认切片一次性任务数
	public $cnum=5;

	public $max_task=500;


	private $error_code=array(
		'100'=>'OK',
		'101'=>'DB ERROR',
		'102'=>'param is empty',
		'103'=>'the task is not exists',
		'104'=>'the task is progress',
        '105' => 'the task is cancel',
        '106' => 'the parent unit is not audit',
        '107' => 'other task is not audit',
	);
	
	public $object_parent =null;

	public function __construct($object_parent=null) {
         $this->debug_log =new np_log_class();
         if(is_object($object_parent))
         {
             $this->object_parent = $object_parent;
         }
    }


    private function __write_log($msg,$deep='error'){
    	$this->debug_log->set_path(dirname(dirname(__FILE__)).'/data/log/op_queue/'.$deep.'/');
    	$this->debug_log->write($msg);
    }

    private function __error($msg){
    	$this->__write_log($msg);
    }
    private function __debug($msg){
    	$this->__write_log($msg,'debug');
    }



    private function __return($state,$data=NULL){
    	if (isset($this->error_code[$state])){
    		$reason=$this->error_code[$state];
    	}else{
    		$reason='UNKOWN';
    	}

    	return array('state'=>$state,'reason'=>$reason,'data'=>$data);
    }


    private function __build_fileds($params,$include_fields){
    	foreach ($params as $k=>$v){
    		if (strpos($k,'nns_')!==0){
    			$k1='nns_'.$k;
    		}else{
    			$k1=$k;
    		}
    		if (!in_array($k1,$include_fields)){
    			unset($params[$k]);
    		}
    	}
    	return $params;
    }


    /**
	 * 根据唯一ID创建其他的ID
	 * @param DB
	 * @param array()
	 * org_id SP的ID
	 * ex_id 单位ID
	 * type  单位类型
	 * action 操作
	 * @return  array()
	 */
    private function __build_unit_ids($db,$params){
    	switch ($params['type']){
    		case BK_OP_VIDEO:
    			$params['video_id']=$params['ex_id'];
				$params['media_id']="";
    			$params['index_id']="";
    		break;
    		case BK_OP_INDEX:
    			$sql='select nns_vod_id from nns_vod_index where nns_id=\''.$params['ex_id'].'\'';
    			$re=nl_query_by_db($sql,$db);

    			if (!is_array($re)){
    				$this->__error("[__build_unit_ids] DB execute fail \nsql:\n".$sql);
    				 return FALSE;
    			}
    			$params['index_id']=$params['ex_id'];
    			$params['video_id']=$re[0]['nns_vod_id'];
				$params['media_id']="";
    		break;
    		case BK_OP_MEDIA:
    			$sql='select nns_vod_id,nns_vod_index_id from nns_vod_media where nns_id=\''.$params['ex_id'].'\'';
    			$re=nl_query_by_db($sql,$db);

    			if (!is_array($re)){
    				$this->__error("[__build_unit_ids] DB execute fail \nsql:\n".$sql);
    				return FALSE;
    			}

    			$params['media_id']=$params['ex_id'];
    			$params['index_id']=$re[0]['nns_vod_index_id'];
    			$params['video_id']=$re[0]['nns_vod_id'];
    		break;
    		case BK_OP_LIVE:
    			$params['video_id']=$params['ex_id'];
				$params['media_id']="";
    			$params['index_id']="";
    		    break;
    		case BK_OP_LIVE_MEDIA:
    		    $sql='select nns_live_id,nns_live_index_id from nns_live_media where nns_id=\''.$params['ex_id'].'\'';
    		    $re=nl_query_by_db($sql,$db);
    		
    		    if (!is_array($re)){
    		    				$this->__error("[__build_unit_ids] DB execute fail \nsql:\n".$sql);
    		    				return FALSE;
    		    }
    		
    		    $params['media_id']=$params['ex_id'];
    		    $params['index_id']=$re[0]['nns_live_index_id'];
    		    $params['video_id']=$re[0]['nns_live_id'];
    		    break;
		    case BK_OP_PLAYBILL:
		        $sql='select nns_live_id,nns_live_media_id from nns_live_playbill_item where nns_id=\''.$params['ex_id'].'\'';
		        $re=nl_query_by_db($sql,$db);
		    
		        if (!is_array($re)){
		            $this->__error("[__build_unit_ids] DB execute fail \nsql:\n".$sql);
		            return FALSE;
		        }
		    
		        $params['media_id']=$params['ex_id'];
		        $params['index_id']=$re[0]['nns_live_media_id'];
		        $params['video_id']=$re[0]['nns_live_id'];
		        break;
	        case BK_OP_FILE:
	            $params['video_id']=$params['ex_id'];
				$params['media_id']="";
    			$params['index_id']="";
    			break;
			case BK_OP_PRODUCT:
			    $params['video_id']=$params['ex_id'];
			    $params['media_id']="";
			    $params['index_id']="";
			    break;
    	}
    	$params['release_time']=date("Y-m-d");
//    	获取影片上映时间 BY S67 2014/2/22
        if($params['type'] !=BK_OP_PLAYBILL || $params['type'] !=BK_OP_LIVE_MEDIA || $params['type'] !=BK_OP_PRODUCT || $params['type'] !=BK_OP_FILE || $params['type'] !=BK_OP_LIVE)
        {
        	$sql="select nns_show_time from nns_vod where nns_id='{$params['video_id']}'";
        	$re=nl_query_by_db($sql,$db);
    
        	if (!is_array($re)){
        		$this->__error("[__build_unit_ids] DB query fail \nsql:\n".$sql);
        		
        	}else{
        		$params['release_time']=(strlen($re[0]['nns_show_time']) <1) ? null : $re[0]['nns_show_time'];
        	}
        }
    	return $params;

    }

//  计算当前任务应有的权重\审核状态
    private function __ready_add_op_queue($db,$params){

    	$ex_video_sql=" (nns_video_id='{$params['video_id']}' and nns_type='".BK_OP_VIDEO."')  ";
    	$ex_index_sql=" (nns_video_id='{$params['video_id']}' and nns_index_id='{$params['index_id']}' and  nns_type='".BK_OP_INDEX."') ";
    	$ex_media_sql=" (nns_video_id='{$params['video_id']}' and nns_index_id='{$params['index_id']}' and  nns_media_id='{$params['media_id']}' and nns_type='".BK_OP_MEDIA."') ";

    	$ex_sql="  nns_org_id='{$params['org_id']}' and ";
    	switch ($params['type']){
    		case BK_OP_VIDEO:
    			$ex_sql .=$ex_video_sql;
    		break;
    		case BK_OP_INDEX:
    			$ex_sql .=$ex_video_sql ." or ".$ex_index_sql;
    		break;
    		case BK_OP_MEDIA:
    			$ex_sql .=$ex_video_sql ." or ".$ex_index_sql." or ".$ex_media_sql;
    		break;
    	}

    	$sql="select nns_type,nns_weight from ".$this->weight_table." where ".$ex_sql;

    	$re=nl_query_by_db($sql,$db);

//    	根据排列计算当前操作应具备的权重

		if ($re===FALSE){
    		$this->__error("[__ready_add_op_queue] DB execute fail \nsql:\n".$sql);
    		return FALSE;
    	}elseif ($re===TRUE){
    		$params['weight']=$this->__get_real_weight($params['weight'],$params);
    		return $params;
    	}

		$weight_arr=array();
//		容错检查，检查同类单位下是否存在不同的权重，届时做批量容错处理 BY S67
//		$weight_error=array();
		foreach ($re as $item){
			if (isset($weight_arr[$item['nns_type']]) && $weight_arr[$item['nns_type']]<$item['nns_weight']){
//			if (isset($weight_arr[$item['nns_type']]) && $weight_arr[$item['nns_type']]!=$item['nns_weight']){
//				$weight_arr[$item['nns_type']]=$item['nns_weight']>$weight_arr[$item['nns_type']]?$item['nns_weight']:$weight_arr[$item['nns_type']];
//				$weight_error[$item['nns_type']]=$weight_arr[$item['nns_type']];
				$weight_arr[$item['nns_type']]=$item['nns_weight'];
			}elseif (!isset($weight_arr[$item['nns_type']])){
				$weight_arr[$item['nns_type']]=$item['nns_weight'];
			}
		}

		if (isset($weight_arr['media'])) {$weight_real=$weight_arr['media'];}
		elseif (isset($weight_arr['index'])){ $weight_real=$weight_arr['index'];}
		elseif (isset($weight_arr['video'])){ $weight_real=$weight_arr['video'];}


		$params['weight']=$this->__get_real_weight($weight_real,$params);;
//		var_dump($weight_error);die;

//		开始做容错处理
//		foreach ($weight_error as $type=>$v){
//			$sql_name="ex_".$type."_sql";
//			$update_sql="update ".$this->table." set nns_weight='{$v}' where ".$$sql_name;
//			nl_execute_by_db($update_sql,$db);
//		}


//		计算是否前置有待审核操作 BY S67 2014-04-30
//		若有，则当前操作也设置为待审核状态
		$sql_name='ex_'.$params['type'].'_sql';
		$sql="select count(1) as num from ".$this->table." where ".$ex_sql.$$sql_name." and nns_status='".BK_OP_UNAUDIT."'";
    	$re=nl_query_by_db($sql,$db);		
		if ($re[0]["num"]>0){
			$params['status']=BK_OP_UNAUDIT;
		}



		return $params;

    }


    private function __get_real_weight($weight,$params){
    	$weight=empty($weight)?0:$weight;
 		return $weight;
//    	if ($params['action']==BK_OP_DELETE){
//			$down=false;
//		}else{
//			$down=true;
//		}
//
//		switch ($params['type']){
//			case BK_OP_VIDEO:
//    			if ($down==FALSE){
//    				return $weight+1;
//    			}else{
//    				return $weight+3;
//    			}
//    		break;
//    		case BK_OP_INDEX:
//    			return $weight+2;
//
//    		break;
//    		case BK_OP_MEDIA:
//    			if ($down==FALSE){
//    				return $weight+3;
//    			}else{
//    				return $weight+1;
//    			}
//    		break;
//		}
    }

/**
 * 检查操作的重复性，删除重复性等待操作
 * @return FALSE 没有重复的命令，需要执行添加
 * 			TRUE  有重复的命令，不需要执行添加
 */
    private function __check_action_repeat($db,$params){
    	$ex_video_sql=" nns_org_id='{$params['org_id']}' and nns_video_id='{$params['video_id']}' and nns_type='".BK_OP_VIDEO."'  ";
    	$ex_index_sql=" nns_org_id='{$params['org_id']}' and nns_video_id='{$params['video_id']}' and nns_index_id='{$params['index_id']}' and  nns_type='".BK_OP_INDEX."' ";
    	$ex_media_sql=" nns_org_id='{$params['org_id']}' and nns_video_id='{$params['video_id']}' and nns_index_id='{$params['index_id']}' and  nns_media_id='{$params['media_id']}' and nns_type='".BK_OP_MEDIA."' ";

//    	$query_sql="select * from ".$this->table;

    	switch ($params['type']){
    		case BK_OP_VIDEO:
    			$where_sql = " where ".$ex_video_sql." and nns_status='{$params['status']}'";
    		break;
    		case BK_OP_INDEX:
    			$where_sql = " where ".$ex_index_sql." and nns_status='{$params['status']}'";
    		break;
    		case BK_OP_MEDIA:
    			$where_sql = " where ".$ex_media_sql." and (nns_action!='".BK_OP_DELETE."' and (nns_status='".BK_OP_WAIT_CLIP."' or nns_status='".BK_OP_UNAUDIT."')) ";

    			if ($params['action']==BK_OP_DELETE){
    				$where_sql = " where ".$ex_media_sql." and (nns_status='".BK_OP_WAIT_CLIP."' or nns_status='".BK_OP_CLIP."' or nns_status='".BK_OP_WAIT."' or nns_status='".BK_OP_UNAUDIT."') ";
    			}
    		break;
    		default:
    		    return false;
    	}

//    	$re=nl_query_by_db($query_sql.$where_sql,$db);
//
//    	if ($re===FALSE){
//    		$this->__error("[__check_action_repeat] DB execute fail \nsql:\n".$query_sql.$where_sql);
//    		return FALSE;
//    	}elseif ($re===TRUE){
//    		return FALSE;
//    	}

//		转存日志 BY S67 2014/2/24
		$record_sql="select * from ".$this->table.$where_sql." order by nns_op_mtime";
		$re_info=nl_query_by_db($record_sql,$db);


    	$date=date('Y-m-d H:i:s');
    	if ($params['action']==BK_OP_DELETE){
    		$sql="delete from ".$this->table.$where_sql;
//			$sql="update ".$this->table." set nns_op_mtime='{$params['op_mtime']}',nns_create_time='{$date}' ".$where_sql." and nns_action='".BK_OP_DELETE."'";

			$re=nl_execute_by_db($sql,$db);
    	}else{

    		if (is_array($re_info)){
//    			foreach ($re_info as $info){
//    				$info['nns_op_mtime']=$params['op_mtime'];
//    				$info['nns_create_time']=$date;
    				$sql="update ".$this->table." set nns_op_mtime='{$params['op_mtime']}',nns_create_time='{$date}',nns_release_time='{$params['release_time']}' ".$where_sql." and (nns_action='".BK_OP_ADD."' or nns_action='".BK_OP_MODIFY."')";
//    			}
    				$re=nl_execute_by_db($sql,$db);
    		}

//    		$sql="update ".$this->table." set nns_op_mtime='{$params['op_mtime']}',nns_create_time='{$date}' ".$where_sql." and (nns_action='".BK_OP_ADD."' or nns_action='".BK_OP_MODIFY."')";
    	}



    	if ($re===FALSE){
    		$this->__error("[__check_action_repeat] DB execute fail \nsql:\n".$sql);
    		return FALSE;
    	}elseif ($re===TRUE){

    		$this->__add_task_ok_log($db,$re_info,BK_OP_CANCEL);
    		$re_info=NULL;
    		if ($params['action']==BK_OP_DELETE){
    			return FALSE;
    		}else{
    			$rows=$db->affected_rows();
    			if ($rows>0){
    				$this->__debug("[__check_action_repeat] action repeat num:{$rows} \nsql:\n".$sql);
    				return TRUE;
    			}else{
    				return FALSE;
    			}

    		}
    	}
    	else
    	{
    		return false;
    	}
    }
    
    public function is_json($string)
    {
        $string = strlen($string) <1 ? '' : $string;
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }

	/**
	 * 添加操作队列
	 * @param DB
	 * @param array()
	 * org_id SP的ID
	 * ex_id 单位ID
	 * type  单位类型
	 * action 操作
	 * @return  array()
	 * state 错误码
	 * reason 错误说明
	 * data  数据 NULL
	 */
	public function add($db,$params){

		$lp=np_check_params_policy(array(
			array(
				'value'=>$db,
				'key'=>'db',
				'rule'=>'noempty'
			),
			array(
				'value'=>$params['org_id'],
				'key'=>'org_id',
				'rule'=>'noempty'
			),
			array(
				'value'=>$params['ex_id'],
				'key'=>'ex_id',
				'rule'=>'noempty'
			),
			array(
				'value'=>$params['type'],
				'key'=>'type',
				'rule'=>'noempty'
			),
			array(
				'value'=>$params['action'],
				'key'=>'action',
				'rule'=>'noempty'
			),
		));
		$arr_nns_ext_info =  (isset($params['nns_ext_info']) && strlen($params['nns_ext_info']) >0 && $this->is_json($params['nns_ext_info'])) ? json_decode($params['nns_ext_info'],true) : null;
		
		$str_nns_url =  (isset($params['nns_url']) && strlen($params['nns_url']) >0 && stripos($params['nns_url'], 'http://') === FALSE && stripos($params['nns_url'], 'https://') === FALSE && stripos($params['nns_url'], 'ftp://') === FALSE) ? $params['nns_url'] : '';
		
		$nns_media_encode_flag = (isset($params['nns_media_encode_flag']) && ($params['nns_media_encode_flag'] == '1' || $params['nns_media_encode_flag'] == '2')) ? true : false;
		$nns_live_to_media = (isset($params['nns_live_to_media']) &&  $params['nns_live_to_media'] == '2')? '2' : '1';
		unset($params['nns_url']);
		unset($params['nns_media_encode_flag']);
		unset($params['nns_live_to_media']);
		unset($params['nns_ext_info']);
		if ($lp['state']===FALSE){
			$this->__error("[add] params is wrong \n ".$lp['reason']);
			return $this->__return('102');
		}

		$params=$this->__build_unit_ids($db,$params);
		if ($params===FALSE){
			return $this->__return('101');
		}
//        方法有误  先注释掉 BY S67 2014-03-29
//        $checkResult = $this->checkBlackList($db, $params['org_id'], $params['type'], $params['video_id'], $params['index_id'], $params['media_id']);
//        if (!$checkResult) {
//            return $this->__return('105');
//        }
		$config = $this->__get_config($params['org_id']);

		$result_cp = nl_cp::query_by_id_by_db($db, $params['nns_cp_id']);
		$result_cp = (isset($result_cp['data_info']['nns_config']) && !empty($result_cp['data_info'])) ? json_decode($result_cp['data_info']['nns_config'], true) : null;
		
		$params=$this->__build_fileds($params,$this->fileds);
		$params['create_time']=date('Y-m-d H:i:s');

//		if (!isset($params['status']) && strlen($params['status'])==0){
//		当为片源，且操作为添加或修改时，则需要切片操作，若切片关闭且需要注入队列时，则不需要切片
		if (($params['type']===BK_OP_MEDIA || $params['type']===BK_OP_FILE) && ($params['action']===BK_OP_ADD || $params['action']===BK_OP_MODIFY) && (int)$config['disabled_clip'] !== 2 && (int)$config['disabled_clip'] !== 3)
		{
		    if(isset($config['check_file_exsist']) && $config['check_file_exsist'] =='1' && isset($config['clip_file_repeat_enable']) && $config['clip_file_repeat_enable'] == '0' && isset($config['cdn_check_ts_accord_address']) && strlen($config['cdn_check_ts_accord_address']) && 
		        ((isset($arr_nns_ext_info['path']) && strlen($arr_nns_ext_info['path']) >0) || strlen($str_nns_url) >0))
		    {
		        $temp_url_check = (isset($arr_nns_ext_info['path']) && strlen($arr_nns_ext_info['path']) >0) ? $arr_nns_ext_info['path'] : $str_nns_url;
		        $str_media_download_url = rtrim($config['cdn_check_ts_accord_address'],'/').'/'.ltrim($temp_url_check,'/');
		        $str_media_download_url = str_replace("//","/",$str_media_download_url);
		        $result_check_ftp_file = c2_task_model::check_ftp_file($str_media_download_url, null);
		        $params['status'] = ($result_check_ftp_file['ret'] !=0) ? BK_OP_WAIT_CLIP : BK_OP_WAIT;
		    }
		    else
		    {
		        $params['status'] = $nns_media_encode_flag ? BK_OP_WAIT : BK_OP_WAIT_CLIP;
		    }
		}
		else
		{
			$params['status']=BK_OP_WAIT;
		}
		//直播转点播逻辑
		if($params['type']===BK_OP_MEDIA && ($params['action']===BK_OP_ADD || $params['action']===BK_OP_MODIFY) && $nns_live_to_media == '2')
		{
		    $params['status']=BK_OP_WAIT_SP_ENCODE;
		}
		if($params['status'] == BK_OP_WAIT && $params['type']===BK_OP_MEDIA && ($params['action']===BK_OP_ADD || $params['action']===BK_OP_MODIFY) && isset($config['clip_file_encode_model']) && $config['clip_file_encode_model'] == '2' && isset($result_cp['cp_transcode_file_enabled']) && $result_cp['cp_transcode_file_enabled'] == '1')
		{
		    $params['status']=BK_OP_WAIT_SP_ENCODE_BEGIN;
		}
//		}
		$params['op_mtime']=round(np_millisecond_f()*1000);
		if(empty($params['id']))
		{
			$params['id']=np_guid_rand();
		}

		$re=$this->__check_action_repeat($db,$params);
		if ($re===TRUE){
			return $this->__return('100');
		}
//		检查当前单位的权重
		if ($params['type']===BK_OP_MEDIA || $params['type']===BK_OP_INDEX || $params['type']===BK_OP_VIDEO ){
		  $params=$this->__ready_add_op_queue($db,$params);
		}

		//			根据配置判断是否应该被暂停 BY S67 2014-03-22
		if ($config['op_pause_weight']>$params['weight']){
			$params['state']=1;
		}
		
//		判断SP是否为待审核状态 BY S67 2014-04-10
		if ($config['op_audit_disable']==1){
			$params['status']=BK_OP_UNAUDIT;
		}
		
//		判断单个操作是否为待审核状态 BY S67 2014-04-30
		$config_key=$params['type'].'_'.$params['action'];
		if (is_array($config[$config_key]) && $config[$config_key]['audit']==1){
			$params['status']=BK_OP_UNAUDIT;
		}
		
		if (strlen(trim($config['before_execute_sp']))>0){
			$params['status']=BK_OP_WAIT_SP;
			$params['from']=$config['before_execute_sp'];
		}
		$re=nl_db_insert($db,$this->table,$params);

		if ($re===TRUE)
		{
		    if ($params['type']===BK_OP_MEDIA || $params['type']===BK_OP_INDEX || $params['type']===BK_OP_VIDEO )
		    {
    			$log=array();
    			foreach ($params as $key=>$value)
    			{
    				if (strpos($key,'nns_') !== 0)
    				{
    					$log['nns_'.$key]=$value;
    				}
    				else
    				{
    					$log[$key] = $value;
    				}
    			}
    
    //			记录日志 BY S67 2014/2/12
    			$this->__add_task_ok_log($db,array($log),$params['status']);
		    }
			return $this->__return('100');
		}else{
			$this->__error("[add] DB execute fail \n".var_export($params,true) );
			return $this->__return('101');
		}
	}

    /**
     * @param $db
     * @param $sp_id
     * @param $type
     * @param $video_id
     * @param $index_id
     * @param $media_id
     * @return bool
     */
    private function checkBlackList($db, $sp_id, $type, $video_id, $index_id, $media_id)
    {
        $sql = "SELECT COUNT(1) as num FROM nns_mgtvbk_op_blacklist WHERE nns_org_id = '{$sp_id}' ";
        switch ($type) {
            case BK_OP_VIDEO:
                $sql .= "AND nns_video_id = '{$video_id}' AND nns_type = '1'";
                break;

            case BK_OP_INDEX:
                $sql .= "AND( nns_video_id = '{$video_id}' AND nns_type = '1') ";
                $sql .= "OR (nns_video_id = '{$video_id}' AND nns_video_index_id = '{$index_id}' ";
                $sql .= "AND nns_type = '2')";
                break;

            case BK_OP_MEDIA:
                $sql .= "AND( nns_video_id = '{$video_id}' AND nns_type = '1') ";
                $sql .= "OR (nns_video_id = '{$video_id}' AND nns_video_index_id = '{$index_id}' ";
                $sql .= "AND nns_type = '2') ";
                $sql .= "OR( nns_video_id = '{$video_id}' AND nns_video_index_id = '{$index_id}' AND nns_video_media_id = '{$media_id}'";
                $sql .= "AND nns_type = '3')";
                break;

            default:
                return false;
        }

        $checkResult = nl_query_by_db($sql, $db);

        //查询到有结果、或者查询出错
        if ((isset($checkResult[0]['num']) && $checkResult[0]['num'] > 0) || $checkResult === false) {
            return false;
        } else {
            return true;
        }
    }

/*
 * 切片相关方法
 *****************************************************************************************************/

	/**
	 * 重新切片
	 */
	public function re_clip($db,$op_id){
		$lp=np_check_params_policy(array(
			array(
				'value'=>$db,
				'key'=>'db',
				'rule'=>'noempty'
			),
//			array(
//				'value'=>$org_id,
//				'key'=>'org_id',
//				'rule'=>'noempty'
//			),
			array(
				'value'=>$op_id,
				'key'=>'op_id',
				'rule'=>'noempty'
			),
		));

		if ($lp['state']===FALSE){
			$this->__error("[re_clip] params is wrong \n ".$lp['reason']);
			return $this->__return('102');
		}

		//		准备数据，用于日志转移
		$sql='select * from '.$this->table.
				' where nns_type=\''.BK_OP_MEDIA.'\' ' .
				'and nns_id=\''.$op_id.'\' ' ;
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_'.$type.'_id=\''.$ex_id.'\' ' .
//				'and nns_type=\''.$type.'\'';

		$re_info=nl_query_by_db($sql,$db);

		if (!is_array($re_info)){
			$this->__error("[re_clip] task is not exists \n ".$sql);
			return $this->__return('103');
		}


		$sql='update '.$this->table.' set nns_status=\''.BK_OP_WAIT_CLIP.'\',nns_weight=\''.BK_OP_RE_CLIP_WEIGHT.'\' ' .
				'where nns_type=\''.BK_OP_MEDIA.'\' ' .
				'and nns_id="'.$op_id.'" ' ;
//				'and nns_type="'.BK_OP_MEDIA.'" ' .
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_media_id=\''.$media_id.'\' ';

		$re=nl_execute_by_db($sql,$db);

		if ($re===TRUE){

//			记录日志 BY S67 2014/2/12
//			$this->__add_task_ok_log($db,$re_info,BK_OP_WAIT_CLIP);


			$rows=$db->affected_rows();
			if ($rows!==1){

				$this->__error("[re_clip] execute number is wrong \nnum:".$rows."\nsql:".$sql);
				return $this->__return('103');
			}
			return $this->__return('100');
		}else{
			$this->__error("[re_clip] DB execute fail \nsql:\n".$sql);
			return $this->__return('101');
		}

	}

    /**
	 * 正在切片
	 * @param DB
	 * @param SP的ID
	 * @param 片源ID
	 * @return  array()
	 * state 错误码
	 * reason 错误说明
	 * data  数据 NULL
	 */
	public function clip_progress($db,$op_id){
		$lp=np_check_params_policy(array(
			array(
				'value'=>$db,
				'key'=>'db',
				'rule'=>'noempty'
			),
//			array(
//				'value'=>$org_id,
//				'key'=>'org_id',
//				'rule'=>'noempty'
//			),
			array(
				'value'=>$op_id,
				'key'=>'op_id',
				'rule'=>'noempty'
			),
		));

		if ($lp['state']===FALSE){
			$this->__error("[clip_progress] params is wrong \n ".$lp['reason']);
			return $this->__return('102');
		}


//		准备数据，用于日志转移
		$sql='select * from '.$this->table.
				' where nns_status=\''.BK_OP_WAIT_CLIP.'\' ' .
				'and nns_id=\''.$op_id.'\' ' ;
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_'.$type.'_id=\''.$ex_id.'\' ' .
//				'and nns_type=\''.$type.'\'';

		$re_info=nl_query_by_db($sql,$db);

		if (!is_array($re_info)){
			$this->__error("[clip_progress] task is not exists \n ".$sql);
			return $this->__return('103');
		}


//		$is_execute='select 1 from '.$this->table.' where nns_status="'.BK_OP_CLIP.'" ' .
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_media_id=\''.$media_id.'\' ';
//
//		$re=nl_query_by_db($is_execute,$db);
//
//		if (is_array($re)){
//			return $this->__return('104');
//		}


		$sql='update '.$this->table.' set nns_status=\''.BK_OP_CLIP.'\' ' .
				'where nns_status=\''.BK_OP_WAIT_CLIP.'\' ' .
				'and nns_id="'.$op_id.'" ' ;
//				'and nns_type="'.BK_OP_MEDIA.'" ' .
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_media_id=\''.$media_id.'\' ';

		$re=nl_execute_by_db($sql,$db);

		if ($re===TRUE){

//			记录日志 BY S67 2014/2/12
			$this->__add_task_ok_log($db,$re_info,BK_OP_CLIP);


			$rows=$db->affected_rows();
			if ($rows!==1){

				$this->__error("[clip_progress] execute number is wrong \nnum:".$rows."\nsql:".$sql);
				return $this->__return('103');
			}
			return $this->__return('100');
		}else{
			$this->__error("[clip_progress] DB execute fail \nsql:\n".$sql);
			return $this->__return('101');
		}
	}

	/**
	 * 通知切片成功
	 * @param DB
	 * @param SP的ID
	 * @param 片源ID
	 * @return  array()
	 * state 错误码
	 * reason 错误说明
	 * data  数据 NULL
	 */
	public function clip_ok($db,$op_id){
		$lp=np_check_params_policy(array(
			array(
				'value'=>$db,
				'key'=>'db',
				'rule'=>'noempty'
			),
//			array(
//				'value'=>$org_id,
//				'key'=>'org_id',
//				'rule'=>'noempty'
//			),
			array(
				'value'=>$op_id,
				'key'=>'op_id',
				'rule'=>'noempty'
			),
		));

		if ($lp['state']===FALSE){
			$this->__error("[clip_ok] params is wrong \n ".$lp['reason']);
			return $this->__return('102');
		}


		//		准备数据，用于日志转移
		$sql='select * from '.$this->table.
//				' where nns_status=\''.BK_OP_CLIP.'\' ' .
				' where nns_id=\''.$op_id.'\' ' ;
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_'.$type.'_id=\''.$ex_id.'\' ' .
//				'and nns_type=\''.$type.'\'';

		$re_info=nl_query_by_db($sql,$db);
		
		//print_r($re_info);
		
		
		
		//echo $sql;die;

		if (!is_array($re_info)){
			$this->__error("[clip_ok] task is not exists \n ".$sql);
			return $this->__return('103');
		}
		
		// if(is_array($re_info)&&$re_info[0]['nns_status']==BK_OP_WAIT){
			// return $this->__return('100');
		// }



		$sql='update '.$this->table.' set nns_status=\''.BK_OP_WAIT.'\', ' .
				'nns_create_time=\''.date('Y-m-d H:i:s').'\''.
				'where nns_status=\''.BK_OP_CLIP.'\' ' .
				'and nns_id="'.$op_id.'" ' ;
//				'and nns_type="'.BK_OP_MEDIA.'" ' .
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_media_id=\''.$media_id.'\' ';

		$re=nl_execute_by_db($sql,$db);

		if ($re===TRUE){

//			记录日志 BY S67 2014/2/12
			$this->__add_task_ok_log($db,$re_info,BK_OP_WAIT);

			$rows=$db->affected_rows();
			if ($rows!==1){

				$this->__error("[clip_ok] execute number is wrong \nnum:".$rows."\nsql:".$sql);
				return $this->__return('103');
			}
			return $this->__return('100');
		}else{
			$this->__error("[clip_ok] DB execute fail \nsql:\n".$sql);
			return $this->__return('101');
		}
	}

	/**
	 * 获取切片任务
	 * @param DB
	 * @param SP的ID
	 * @param 每次取的数量 若为NULL则用默认配置
	 * @return  array()
	 * state 错误码
	 * reason 错误说明
	 * data  数据 NULL
	 */
	public function get_clip($db,$org_id,$num=NULL){
		$num=empty($num)?$this->cnum:$num;

		$lp=np_check_params_policy(array(
			array(
				'value'=>$db,
				'key'=>'db',
				'rule'=>'noempty'
			),
			array(
				'value'=>$org_id,
				'key'=>'org_id',
				'rule'=>'noempty'
			),
		));

		if ($lp['state']===FALSE){
			$this->__error("[get_clip] params is wrong \n ".$lp['reason']);
			return $this->__return('102');
		}

		$config=$this->__get_config($org_id);
		$order=$this->__get_order_config($config);
		$freeze_time=$this->__get_freeze_time_config($config);

//		冻结时间获取
		$freeze_time_sql='';
		if (!empty($freeze_time)){
			$freeze_time=strtotime($freeze_time)*1000;
			$freeze_time_sql=' and nns_op_mtime<'.$freeze_time;
		}

//		延迟时间获取
		$delay_sql='';
		if (defined('BK_OP_CLIP_TASK_DELAY') && BK_OP_CLIP_TASK_DELAY>0){
			$delay_mtime=(time()-(int)BK_OP_CLIP_TASK_DELAY)*1000;
			$delay_sql='and nns_op_mtime <= '.$delay_mtime ;
		}



		$sql='select * from '.$this->table.
				' where (nns_type="'.BK_OP_MEDIA.'" or nns_type="'.BK_OP_FILE.'") ' .
				'and nns_status="'.BK_OP_WAIT_CLIP.'" ' .
				'and nns_org_id="'.$org_id.'" ' .$delay_sql.$freeze_time_sql.
				' and nns_state="0" ' .
				'  order by ' .$order.

				' limit '.$num;
// 		die($sql);
		$re=nl_query_by_db($sql,$db);

		if ($re===FALSE){
			$this->__error("[get_clip] DB execute fail \nsql:\n".$sql);
			return $this->__return('101');
		}elseif ($re===TRUE){
			$re=array();
		}

		return $this->__return('100',$re);

	}


/*
 * 任务相关方法
 *****************************************************************************************************/
	/**
	 * 批量获取新的操作任务
	 * @param DB
	 * @param SP的ID
	 * @param 每次取的数量 若为NULL则用默认配置
	 * @return  array()
	 * state 错误码
	 * reason 错误说明
	 * data  数据 NULL
	 */
	public function get_task($db,$sp_id,$limit=NULL){

		$config=$this->__get_config($sp_id);


		$limit=empty($limit)?$this->max_task:$limit;
		$since=0;
		//参数检测
		$lp=np_check_params_policy(array(
			array(
				'value'=>$db,
				'key'=>'db',
				'rule'=>'noempty'
			),
			array(
				'value'=>$sp_id,
				'key'=>'sp_id',
				'rule'=>'noempty'
			),
		));

		if ($lp['state']===FALSE){
			$this->__error("[get_task] params is wrong \n ".$lp['reason']);
			return $this->__return('102');
		}

//		$is_execute='select 1 from '.$this->table.' where nns_org_id="'.$sp_id.'"  and nns_status!="'.BK_OP_WAIT.'" ' .
//				'and nns_video_id=a.nns_video_id and nns_index_id=a.nns_index_id and nns_media_id=a.nns_media_id ';
//
//
//
//		$sql='select * from '.$this->table.' as a where nns_org_id="'.$sp_id.'" ' .
//				'and  not exists ('.$is_execute.') order by nns_op_mtime limit '.$limit;

//		$sql='select * from ('.$table.
//			 ') as a group by nns_ex_id';
//		echo $sql;die;

//		$re=nl_query_by_db($sql,$db);

		$re=array();
		$mark=array();
		$bool=TRUE;

		$order=$this->__get_order_config($config);
		$freeze_time=$this->__get_freeze_time_config($config);






		$delay_sql='';
		//延迟时间获取
		if (defined('BK_OP_IMPORT_TASK_DELAY') && BK_OP_IMPORT_TASK_DELAY>0){
			$delay_mtime=(time()-(int)BK_OP_CLIP_TASK_DELAY)*1000;
			$delay_sql=' and nns_op_mtime <= '.$delay_mtime ;
		}

		//		冻结时间获取
		$freeze_time_sql='';
		if (!empty($freeze_time)){
			$freeze_time=strtotime($freeze_time)*1000;
			$freeze_time_sql=' and nns_op_mtime<'.$freeze_time;
		}
		$delay_sql=$freeze_time_sql;


//		放行策略
		$policy='';
		if ($config['op_video_disable']==1){
			$policy .= " and nns_type !='".BK_OP_VIDEO."' ";
		}

		if ($config['op_index_disable']==1){
			$policy .= " and nns_type !='".BK_OP_INDEX."' ";
		}

		if ($config['op_media_disable']==1){
			$policy .= " and nns_type !='".BK_OP_MEDIA."' ";
		}

		$delay_sql .=$policy;


		$real_limit=$limit*10;
		while($bool){
			$r=$this->__get_task($db,$sp_id,$since,$real_limit,$order,$delay_sql);
			if (is_array($r)){
				$data=$this->__push_return_task($mark,$r);
				$mark=$data['mark'];
				$re=array_merge($re,$data['data']);
				$since +=$real_limit;

				$len=count($re);
				if ($len==$limit){
					$bool=FALSE;
				}
				if ($len>$limit){
					$bool=FALSE;
					array_splice($re,$limit,$len-$limit);
				}

			}elseif($r===TRUE){
				$bool=FALSE;
			}else{
				return $this->__return('101');
			}

			$r=NULL;
		}



//		if ($re===FALSE){
////			$this->__error("[get_task] DB execute fail \nsql:\n".$sql);
//			return $this->__return('101');
//		}

		return $this->__return('100',$re);
	}


	private function __push_return_task($mark,$r){
		$r1=array();
		foreach ($r as $k=>$item){
			$key=$item['nns_type'].'|'.$item['nns_video_id'].'|'.$item['nns_index_id'].'|'.$item['nns_media_id'];
			if (!isset($mark[$key])){
				if ($item['nns_status']==BK_OP_WAIT){
					// array_splice($r,$k,1);
					array_push($r1,$item);
				}
				$mark[$key]=1;
			}
		}
		$r=NULL;
		return array('mark'=>$mark,'data'=>$r1);
	}

	private function __get_task($db,$sp_id,$since,$limit,$order,$delay_sql){

		$order=str_replace('nns_','a.nns_',$order);

		$delay_sql=str_replace('nns_','a.nns_',$delay_sql);

		$is_execute='select 1 from '.$this->table.' as b where b.nns_org_id="'.$sp_id.'"  and ' ;
		$is_execute_q1=	'(b.nns_status="'.BK_OP_PROGRESS.'" ' .
				'and b.nns_video_id=a.nns_video_id and b.nns_index_id=a.nns_index_id and b.nns_media_id=a.nns_media_id) ';

//		$is_execute_q2 = '(a.nns_type="'.BK_OP_MEDIA.'" and a.nns_action="'.BK_OP_DELETE.'" and b.nns_action!=a.nns_action and b.nns_video_id=a.nns_video_id and b.nns_index_id=a.nns_index_id and b.nns_type="'.BK_OP_MEDIA.'" ' .
//				')';
//		$is_execute .="({$is_execute_q1} or {$is_execute_q2})";

		$is_execute .=$is_execute_q1;

//		直接用SQL来查询会卡住数据库，故分解成2个SQL来进行查询。 BY S67 2014/3/17
		$sql='select * from '.$this->table.' as a where a.nns_org_id="'.$sp_id.'" ' .
				' and a.nns_state="0" ' .
// 				'  and a.nns_status!="'.BK_OP_UNAUDIT.'" '.
// 				'  and a.nns_status!="'.BK_OP_WAIT_SP.'" '.
				'  and a.nns_status="'.BK_OP_WAIT.'" '.
				'  and  not exists ('.$is_execute.') '.
				$delay_sql.' order by '.$order.' limit '.$since.','.$limit;
		//and a.nns_status="'.BK_OP_WAIT.'"
		echo $sql;
		$re=nl_query_by_db($sql,$db);

		if ($re===FALSE){
			$this->__error("[get_task] DB execute fail \nsql:\n".$sql);
			return FALSE;
		}elseif ($re===TRUE){
			return TRUE;
		}

//		$except_sql="select nns_media_id,nns_index_id,nns_video_id,nns_type from '.$this->table.' where nns_status='".BK_OP_PROGRESS."' and nns_org_id='{$sp_id}' ";
//		$except_media=array();
//		$except_index=array();
//		$except_video=array();
//		$except_child_sql=array();
//		foreach ($re as $item){
//			switch ($item['nns_type']){
//				case BK_OP_MEDIA:
//					$except_media[]=$item['nns_media_id'];
//				break;
//				case BK_OP_INDEX:
//					$except_index[]=$item['nns_index_id'];
//				break;
//				case BK_OP_VIDEO:
//					$except_video[]=$item['nns_video_id'];
//				break;
//			}
//
//		}
//
//			if (count($except_media)>0){
//				$str=explode("','",$except_media);
//				$str=" (nns_media_id in ('".$str."') and nns_type='".BK_OP_MEDIA."') ";
//				$except_child_sql[]=$str;
//			}
//
//			if (count($except_index)>0){
//				$str=explode("','",$except_index);
//				$str=" (nns_index_id in ('".$str."') and nns_type='".BK_OP_INDEX."') ";
//				$except_child_sql[]=$str;
//			}
//
//			if (count($except_video)>0){
//				$str=explode("','",$except_video);
//				$str=" (nns_video_id in ('".$str."') and nns_type='".BK_OP_VIDEO."') ";
//				$except_child_sql[]=$str;
//			}
//
//			$except_child_sql_str=explode(' or ',$except_child_sql);
//			$except_child_sql=NULL;



		return $re;

	}

/**
	 * 通知任务成功
	 * @param DB
	 * @param SP的ID
	 * @param 单位ID
	 * @return  array()
	 * state 错误码
	 * reason 错误说明
	 * data  数据 NULL
	 * $task_info op_queue的数据数组（单条）  消息分组用  
	 * $flag  true 需要走流程  ，  false 在消息分组直接反馈成功（数据直接干掉了）
	 */
	public function task_ok($db,$op_id,$task_info=null,$flag=true){
		$lp=np_check_params_policy(array(
			array(
				'value'=>$db,
				'key'=>'db',
				'rule'=>'noempty'
			),
//			array(
//				'value'=>$org_id,
//				'key'=>'org_id',
//				'rule'=>'noempty'
//			),
			array(
				'value'=>$op_id,
				'key'=>'op_id',
				'rule'=>'noempty'
			),
		));

		if ($lp['state']===FALSE){
			$this->__error("[task_ok] params is wrong \n ".$lp['reason']);
			return $this->__return('102');
		}

//		准备数据，用于日志转移
		$sql='select * from '.$this->table.
				' where nns_status=\''.BK_OP_PROGRESS.'\' ' .
				'and nns_id=\''.$op_id.'\' ' ;
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_'.$type.'_id=\''.$ex_id.'\' ' .
//				'and nns_type=\''.$type.'\'';

		$re_info=nl_query_by_db($sql,$db);
        

		if (!is_array($re_info)){
			$this->__error("[task_ok] task is not exists \n ".$sql);
			return $this->__return('103');
		}


		$sql='delete from '.$this->table.
				' where nns_status=\''.BK_OP_PROGRESS.'\' ' .
				'and nns_id=\''.$op_id.'\' ' ;
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_'.$type.'_id=\''.$ex_id.'\' ' .
//				'and nns_type=\''.$type.'\'';
		$re=nl_execute_by_db($sql,$db);
		if ($re===TRUE){

		    if(isset($task_info['nns_is_group']) && $task_info['nns_is_group'] !=0)
		    {
		        $arr_ex = array(
		            'ret'=>0,
		            'reason'=>'import ok'
		        );
		        $this->edit_message_group_info($task_info, $arr_ex);
		    }
//			记录日志 BY S67 2014/2/12
			$this->__add_task_ok_log($db,$re_info,BK_OP_OK);
            
            //print_r();

			$rows=$db->affected_rows();
			if ($rows!==1){

				$this->__error("[task_ok] execute number is wrong \nnum:".$rows."\nsql:".$sql);
				return $this->__return('103');
			}
			return $this->__return('100');
		}else{
			$this->__error("[task_ok] DB execute fail \nsql:\n".$sql);
			return $this->__return('101');
		}
	}

	public function edit_message_group_info($task_info,$arr_ex)
	{
	    $dc = nl_get_dc(array(
    	        'db_policy' =>  NL_DB_WRITE,
    	        'cache_policy' => NP_KV_CACHE_TYPE_NULL
    	    )
	    );
	    switch ($task_info['nns_type'])
	    {
	        case 'video':
	            $video_id = isset($task_info['nns_ref_id']) ? $task_info['nns_ref_id'] : $task_info['nns_video_id'];
	            $table = 'nns_vod';
	            break;
            case 'index':
                $video_id = isset($task_info['nns_ref_id']) ? $task_info['nns_ref_id'] :  $task_info['nns_index_id'];
                $table = 'nns_vod_index';
                break;
            case 'media':
                $video_id = isset($task_info['nns_ref_id']) ? $task_info['nns_ref_id'] :  $task_info['nns_media_id'];
                $table = 'nns_vod_media';
                break;
            case 'live':
                $video_id = isset($task_info['nns_ref_id']) ? $task_info['nns_ref_id'] :  $task_info['nns_video_id'];
                $table = 'nns_live';
                break;
            case 'live_index':
                $video_id = isset($task_info['nns_ref_id']) ? $task_info['nns_ref_id'] :  $task_info['nns_index_id'];
                $table = 'nns_live_index';
                break;
            case 'live_media':
                $video_id = isset($task_info['nns_ref_id']) ? $task_info['nns_ref_id'] :  $task_info['nns_media_id'];
                $table = 'nns_live_media';
                break;
            case 'playbill':
                $video_id = isset($task_info['nns_ref_id']) ? $task_info['nns_ref_id'] :  $task_info['nns_media_id'];
                $table = 'nns_live_playbill_item';
                break;
            case 'file':
                $video_id = isset($task_info['nns_ref_id']) ? $task_info['nns_ref_id'] :  $task_info['nns_video_id'];
                $table = 'nns_file';
                break;
            default:
                $this->object_parent->arr_nedd_notify_data = array(
                    'ret'=>1,
                    'reason'=>"错误片源类型[影片类型:{$task_info['nns_type']}]",
                );
                return ;
	    }
	    $sql = "select nns_cp_id from {$table} where nns_id='{$video_id}'";
	    $video_info = nl_query_by_db($sql, $dc->db());
	    if(!isset($video_info[0]) || !is_array($video_info[0]) || empty($video_info[0]))
	    {
	        $this->object_parent->arr_nedd_notify_data = array(
                'ret'=>1,
                'reason'=>"查询影片数据库失败或者无数据{$sql}",
            );
	        return ;
	    }
	    $arr_group = array(
	        'message_id'=>$task_info['nns_message_id'],
	        'type'=>$task_info['nns_type'],
	        'video_id'=>$video_id,
	        'cp_id'=>$video_info[0]['nns_cp_id'],
	        'ret'=>$arr_ex['ret'],
	        'desc'=>$arr_ex['reason'],
	    );
	    include_once dirname(dirname(__FILE__)).'/nn_logic/message/nl_message.class.php';
	    include_once dirname(dirname(__FILE__)).'/nn_logic/message/message_group.class.php';
	    include_once dirname(dirname(__FILE__)).'/nn_logic/message/message_group_list.class.php';
	    $result_message = nl_message::query_message_by_message_id($dc, $arr_group['message_id'], $arr_group['cp_id']);
	    if($result_message['ret'] !=0)
	    {
	        $this->object_parent->arr_nedd_notify_data = $result_message;
	        return ;
	    }
	    if(!isset($result_message['data_info']) || !is_array($result_message['data_info']) || empty($result_message['data_info']))
	    {
	         $this->object_parent->arr_nedd_notify_data = $result_message;
	         return ;
	    }
	    $total_num = $result_message['data_info']['nns_content_number'];
	    if($total_num <1)
	    {
	        $this->object_parent->arr_nedd_notify_data = array(
	            'ret'=>1,
	            'reason'=>"消息队列数量为{$total_num}小于1",
	        );
	        return ;
	    }
	    $message_guid = $result_message['data_info']['nns_id'];
	    $message_group = nl_message_group::query_by_cp_message_id($dc,$video_info[0]['nns_cp_id'],$task_info['nns_message_id'], $task_info['nns_org_id']);
	    if($message_group['ret'] !=0)
	    {
	        $this->object_parent->arr_nedd_notify_data = $message_group;
	        return ;
	    }
	    if(!isset($message_group['data_info']) || !is_array($message_group['data_info']) || empty($message_group['data_info']))
	    {
	        $this->object_parent->arr_nedd_notify_data = $message_group;
	        return ;
	    }
	    $message_group_guid = $message_group['data_info']['nns_id'];
	    $where_params_list = array(
	        'nns_message_group_id'=>$message_group_guid,
	        'nns_video_id'=>$video_id,
	    );
	    $edit_params_list = array(
	        'nns_state'=>($arr_ex['ret'] == 0) ? 1 : 2,
	        'nns_desc'=>$arr_ex['reason'],
	    );
	    $message_group_list_edit = nl_message_group_list::edit_by_params($dc, $edit_params_list, $where_params_list);
	    if($message_group_list_edit['ret'] !=0)
	    {
	        $this->object_parent->arr_nedd_notify_data = $message_group_list_edit;
	        return ;
	    }
	    $message_group_state_query = nl_message_group_list::query_state_last_count($dc, $message_group_guid);
	    if($message_group_state_query['ret'] !=0)
	    {
	        $this->object_parent->arr_nedd_notify_data = $message_group_state_query;
	        return ;
	    }
	    if($message_group_state_query['data_info'] < $total_num)
	    {
	        $this->object_parent->arr_nedd_notify_data = array(
	            'ret'=>1,
	            'reason'=>"消息队列完成数量为{$message_group_state_query['data_info']}小于总个数{$total_num}",
	        );
	        return ;
	    }
	    $this->object_parent->arr_nedd_notify_data =  nl_message_group_list::query_group_all($dc, $message_group_guid);
	    $this->object_parent->is_need_notify_data = true;
	    return ;
	}
	
	
	
	/**
	 * 正在执行任务
	 * @param DB
	 * @param SP的ID
	 * @param 单位ID
	 * @return  array()
	 * state 错误码
	 * reason 错误说明
	 * data  数据 NULL
	 */
	public function task_progress($db,$op_id){
		$lp=np_check_params_policy(array(
			array(
				'value'=>$db,
				'key'=>'db',
				'rule'=>'noempty'
			),
//			array(
//				'value'=>$org_id,
//				'key'=>'org_id',
//				'rule'=>'noempty'
//			),
			array(
				'value'=>$op_id,
				'key'=>'op_id',
				'rule'=>'noempty'
			),
		));

		if ($lp['state']===FALSE){
			$this->__error("[task_progress] params is wrong \n ".$lp['reason']);
			return $this->__return('102');
		}


//		$is_execute='select 1 from '.$this->table.' where nns_org_id="'.$org_id.'"  and nns_status="'.BK_OP_PROGRESS.'" ' .
//				'and nns_'.$type.'_id=\''.$ex_id.'\' ' .
//				'and nns_type=\''.$type.'\'';
//
//		$re=nl_query_by_db($is_execute,$db);
//
//		if (is_array($re)){
//			return $this->__return('104');
//		}

//		准备数据，用于日志转移
		$sql='select * from '.$this->table.
				' where nns_status=\''.BK_OP_WAIT.'\' ' .
				'and nns_id=\''.$op_id.'\' ' ;
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_'.$type.'_id=\''.$ex_id.'\' ' .
//				'and nns_type=\''.$type.'\'';

		$re_info=nl_query_by_db($sql,$db);

		if (!is_array($re_info)){
			$this->__error("[task_progress] task is not exists \n ".$sql);
			return $this->__return('103');
		}



		$sql='update '.$this->table.' set nns_status=\''.BK_OP_PROGRESS.'\' ' .
				'where nns_status=\''.BK_OP_WAIT.'\' ' .
				'and nns_id=\''.$op_id.'\'';
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_'.$type.'_id=\''.$ex_id.'\' ' .
//				'and nns_type=\''.$type.'\'';

		$re=nl_execute_by_db($sql,$db);

		if ($re===TRUE){

//			记录日志 BY S67 2014/2/12
			$this->__add_task_ok_log($db,$re_info,BK_OP_PROGRESS);

			$rows=$db->affected_rows();
			if ($rows!==1){

				$this->__error("[task_progress] execute number is wrong \nnum:".$rows."\nsql:".$sql);
				return $this->__return('103');
			}
			return $this->__return('100');
		}else{
			$this->__error("[task_progress] DB execute fail \nsql:\n".$sql);
			return $this->__return('101');
		}
	}

	public function task_cancel($db,$op_id){
		$lp=np_check_params_policy(array(
			array(
				'value'=>$db,
				'key'=>'db',
				'rule'=>'noempty'
			),
//			array(
//				'value'=>$org_id,
//				'key'=>'org_id',
//				'rule'=>'noempty'
//			),
			array(
				'value'=>$op_id,
				'key'=>'op_id',
				'rule'=>'noempty'
			),
		));

		if ($lp['state']===FALSE){
			$this->__error("[task_ok] params is wrong \n ".$lp['reason']);
			return $this->__return('102');
		}

//		准备数据，用于日志转移
		$sql='select * from '.$this->table.
				' where nns_status=\''.BK_OP_PROGRESS.'\' ' .
				'and nns_id=\''.$op_id.'\' ' ;
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_'.$type.'_id=\''.$ex_id.'\' ' .
//				'and nns_type=\''.$type.'\'';

		$re_info=nl_query_by_db($sql,$db);

		if (!is_array($re_info)){
			$this->__error("[task_ok] task is not exists \n ".$sql);
			return $this->__return('103');
		}


		$sql='delete from '.$this->table.
				' where nns_status=\''.BK_OP_PROGRESS.'\' ' .
				'and nns_id=\''.$op_id.'\' ' ;
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_'.$type.'_id=\''.$ex_id.'\' ' .
//				'and nns_type=\''.$type.'\'';

		$re=nl_execute_by_db($sql,$db);

		if ($re===TRUE){

//			记录日志 BY S67 2014/2/12
			$this->__add_task_ok_log($db,$re_info,BK_OP_CANCEL);

			$rows=$db->affected_rows();
			if ($rows!==1){

				$this->__error("[task_ok] execute number is wrong \nnum:".$rows."\nsql:".$sql);
				return $this->__return('103');
			}
			return $this->__return('100');
		}else{
			$this->__error("[task_ok] DB execute fail \nsql:\n".$sql);
			return $this->__return('101');
		}
	}

	/**
	 * 更新单位权重
	 * @param DB
	 * @param array(
	 * 		"org_id"=>SPid
	 * 		"ex_id"=>单位ID
	 * 		"type"=>单位类型
	 * 		"weight"=>权重以10000为开始单位
	 * )
	 * @return TRUE 成功
	 * 			FALSE 失败
	 * 			-1 没有等待执行的任务
	 */
	public function update_weight($db,$params,$always=TRUE){

		$ex_video_sql=" nns_org_id='{$params['org_id']}' and nns_video_id='{$params['ex_id']}' and (nns_weight < '{$params['weight']}' or nns_type='".BK_OP_VIDEO."')  ";
    	$ex_index_sql=" nns_org_id='{$params['org_id']}' and nns_index_id='{$params['ex_id']}' and (nns_weight < '{$params['weight']}' or nns_type='".BK_OP_INDEX."')  ";
    	$ex_media_sql=" nns_org_id='{$params['org_id']}' and nns_media_id='{$params['ex_id']}' and nns_type='".BK_OP_MEDIA."'  ";

    	switch ($params['type']){
    		case BK_OP_VIDEO:
    			$where_sql = " where ".$ex_video_sql;
    		break;
    		case BK_OP_INDEX:
    			$where_sql = " where ".$ex_index_sql;
    		break;
    		case BK_OP_MEDIA:
    			$where_sql = " where ".$ex_media_sql;
    		break;
    	}

    	$sql="update ".$this->table." set nns_weight='{$params['weight']}' ".$where_sql;

    	$re=nl_execute_by_db($sql,$db);

    	if ($re===TRUE){

    		$rows=$db->affected_rows();


    		if ($always===TRUE){
	    		$sql="select 1 from ".$this->weight_table." where nns_type='{$params['type']}' and nns_{$params['type']}_id='{$params['ex_id']}' and nns_org_id='{$params['org_id']}' ";

	    		$re=nl_query_by_db($sql,$db);
	    		if ($re===TRUE){
	    			$params=$this->__build_unit_ids($db,$params);
	    			$params=$this->__build_fileds($params,array(
	    				'nns_video_id',
	    				'nns_weight',
	    				'nns_type',
	    				'nns_index_id',
	    				'nns_media_id',
	    				'nns_org_id'
	    			));

	    			$params['id']=np_guid_rand();

	    			$re=nl_db_insert($db,$this->weight_table,$params);

	    			if ($re===FALSE){
		    			$this->__error("[update_weight] DB execute fail \n insert into ".$this->weight_table);
		    			return FALSE;
		    		}
	    		}


	    		$sql="update ".$this->weight_table." set nns_weight='{$params['weight']}' ".$where_sql;
	    		$re=nl_execute_by_db($sql,$db);

	    		if ($re===TRUE){
	    			if ($rows==0){
	    				return -1;
	    			}
	    			return TRUE;
	    		}else{
	    			$this->__error("[update_weight] DB execute fail \nsql:\n".$sql);
	    			return FALSE;
	    		}
    		}else{
    			if ($rows==0){
	    				return -1;
	    			}
    			return TRUE;
    		}

    	}elseif($re===FALSE){
    		$this->__error("[update_weight] DB execute fail \nsql:\n".$sql);
    		return FALSE;
    	}


	}

	/**
	 * 获取单位权重
	 * @param DB
	 * @param array(
	 * 		"nns_org_id"=>SPid
	 * 		'nns_name' => nns_name
	 * )
	 * @info array vod要求的字段
	 * @return TRUE 成功
	 * 			FALSE 失败
	 */
	public function get_weight($db, $params, $info=null) {
		$str_sql = "select op.nns_id,op.nns_video_id,vod.nns_name,op.nns_weight from ".$this->weight_table." as op left join nns_vod as vod on op.nns_video_id=vod.nns_id";
		$where = ' where ';
		$and = ' and ';
		$sql = null;
		if(is_array($params)) {
			foreach($params as $key => $val) {
				if($key == 'nns_name') {
					$sql .= $and.'(vod.nns_name like "%'.$val.'%" or vod.nns_pinyin like "%'.$val.'%")';
				} else {
					$sql .= $and.'op.'.$key.'="'.$val.'"';
				}
			}
		}
		if(is_array($info) && !empty($info)) {
			foreach($info as $k=>$v) {
				if($v != '') {
					if($k == 'nns_id') {
						$id_str = '';
						$id_arr = explode(',', $v);
						foreach($id_arr as $value) {
							if($value != '') {
								$id_str .= '"'.$value.'"'.',';
							}
						}
						$id_str = rtrim($id_str,',');
						$sql .= $and.'vod.'.$k.' in ('.$id_str.')';
					} else {
						$sql .= $and.'vod.'.$k.'="'.$v.'"';
					}

				}
			}
		}
		//-->start xingcheng.hu 去掉where1=1;
		if(!empty($sql))
		{
			$sql = ltrim($sql,' ');
			$sql =  ltrim($sql,'and');
		}
		//<--end
		$str_sql .= $where.$sql.' order by nns_weight desc';//echo $str_sql;die;
		$result = nl_query_by_db($str_sql,$db);
		return $result;
	}
	/**
	 * 删除单位权重
	 * @param DB
	 * @param array(
	 * 		"nns_org_id"=>SPid
	 * 		'nns_id'=>ex_id
	 * )
	 * @return TRUE 成功
	 * 			FALSE 失败
	 */
	public function delete_weight($db, $params) {
		$ex_video_sql=" nns_org_id='{$params['org_id']}' and nns_video_id='{$params['ex_id']}' and (nns_weight = '{$params['weight']}' or nns_type='".BK_OP_VIDEO."')  ";
		$ex_index_sql=" nns_org_id='{$params['org_id']}' and nns_index_id='{$params['ex_id']}' and (nns_weight = '{$params['weight']}' or nns_type='".BK_OP_INDEX."')  ";
		$ex_media_sql=" nns_org_id='{$params['org_id']}' and nns_media_id='{$params['ex_id']}' and nns_type='".BK_OP_MEDIA."'  ";

		switch ($params['type']){
			case BK_OP_VIDEO:
				$where_sql = " where ".$ex_video_sql;
				break;
			case BK_OP_INDEX:
				$where_sql = " where ".$ex_index_sql;
				break;
			case BK_OP_MEDIA:
				$where_sql = " where ".$ex_media_sql;
				break;
		}

		$sql="update ".$this->table." set nns_weight='0' ".$where_sql;
		$re=nl_execute_by_db($sql,$db);

		if($re===TRUE) {
			$sql = "delete from ".$this->weight_table." where nns_video_id='".$params['ex_id']."' and nns_org_id='".$params['org_id']."'";

			$re=nl_execute_by_db($sql,$db);
			if ($re===TRUE){
				return TRUE;
			}else{
				$this->__error("[delete_weight] DB execute fail \nsql:\n".$sql);
				return FALSE;
			}
		}elseif($re===FALSE){
    		$this->__error("[delete_weight] DB execute fail \nsql:\n".$sql);
    		return FALSE;
    	}
	}
	/**
	 * 一键设置权重时  获取已设置的权重的最大值
	 * @params array
	 * @where array 条件
	 * @return TRUE 成功
	 * 			FALSE 失败
	 */
	public function get_max_weight($db, $params) {
		$sql = 'select max(nns_weight) as num from nns_mgtvbk_op_weight where nns_org_id="'.$params['org_id'].'"';
		$result = nl_query_by_db($sql,$db);
		return $result;
	}
//	任务执行完成，生成TASK日志
	private function __add_task_ok_log($db,$params,$status){
		if (!is_array($params)) return FALSE;

		//$params=$this->__build_fileds($params,$this->fileds);
		//var_dump($params);die;
		//unset($item['nns_state']);
		foreach ($params as $item){
			$sp_config = $this->__get_config($item['nns_org_id']);
			$cp_config = '';
		    //edit by zhouguanghu   删除扩展参数和前置sp
			unset($item['nns_state'],$item['nns_ex_data'],$item['nns_from']);
			$item['nns_op_id']=$item['nns_id'];
			$item['nns_id']=np_guid_rand();
			$item['nns_status']=$status;
			$item['nns_create_time']=date('Y-m-d H:i:s');
			$cdn_id = '';
			$mg_asset_type = '';
			$mg_asset_id = '';
			$mg_part_id = '';
			$mg_file_id = '';
            //如果是状态OK
            $sql = "select nns_category_id,nns_integer_id,nns_asset_import_id,nns_cp_id from nns_vod where nns_id='{$item['nns_video_id']}'";
            $video_info = nl_query_by_db($sql, $db);
            if(is_array($video_info))
            {
                $category_id = $video_info[0]['nns_category_id'];
                $item['nns_category_id'] = $category_id;
                $mg_asset_id = $video_info[0]['nns_asset_import_id'];
                //获取CP配置
                if(!empty($video_info[0]['nns_cp_id']))
                {
                	$cp_sql = "select nns_config from nns_cp where nns_id='{$video_info[0]['nns_cp_id']}' limit 1";
                	$cp_result = nl_query_by_db($cp_sql, $db);
                	if(is_array($cp_result))
                	{
                		$cp_config = json_decode($cp_result[0]['nns_config'], true);
                	}
                }
	            if($item['nns_type'] == BK_OP_VIDEO)
	            {
	            	$mg_asset_type = 1;
	            	switch ($sp_config['import_id_mode']) 
	            	{
						case '1':
							$cdn_id = '000000'.$video_info[0]['nns_integer_id'];
							$cdn_id = str_pad($cdn_id,32,"0");
							break;
						case '2':
							$cdn_id = $video_info[0]['nns_asset_import_id'];
							break;
						case '3':
							$cdn_id = CSP_ID . '0000' . $video_info[0]['nns_integer_id'];
							$cdn_id = str_pad($cdn_id,32,"0");
							break;
						case '4':
							$arr_csp_id = explode("|", CSP_ID);
							$str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
							$lest_num = 32-$str_lenth;
							$cdn_id = $arr_csp_id[0].'1'.str_pad($video_info[0]['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
							break;
						default:
							$cdn_id = $item['nns_video_id'];
							break;
	            	}
	            }
            }
            
            if($item['nns_type'] == BK_OP_INDEX)
            {
            	$index_sql = "select nns_integer_id,nns_import_id from nns_vod_index where nns_id='{$item['nns_index_id']}'";
	            $index_info = nl_query_by_db($index_sql, $db);
	            if(is_array($index_info))
	            {
	            	$mg_part_id = $index_info[0]['nns_import_id'];
		            switch ($sp_config['import_id_mode']) 
	            	{
						case '1':
							$cdn_id = '000000'.$index_info[0]['nns_integer_id'];
							$cdn_id = str_pad($cdn_id,32,"0");
							break;
						case '2':
							$cdn_id = $index_info[0]['nns_import_id'];
							break;
						case '3':
							$cdn_id = CSP_ID . '0000' . $index_info[0]['nns_integer_id'];
							$cdn_id = str_pad($cdn_id,32,"0");
							break;
						case '4':
							$arr_csp_id = explode("|", CSP_ID);
							$str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
							$lest_num = 32-$str_lenth;
							$cdn_id = $arr_csp_id[0].'1'.str_pad($index_info[0]['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
							break;
						default:
							$cdn_id = $item['nns_index_id'];
							break;
	            	}
	            }	            
	            $mg_asset_type = 2;
            }
            //如果是片源,则查询片源的文件时长和文件大小
            if($item['nns_type'] == BK_OP_MEDIA)
            {
            	$index_sql = "select nns_integer_id,nns_import_id from nns_vod_index where nns_id='{$item['nns_index_id']}'";
	            $index_info = nl_query_by_db($index_sql, $db);
	            if(is_array($index_info))
	            {
	            	$mg_part_id = $index_info[0]['nns_import_id'];
	                $media_sql = "select nns_file_size,nns_file_time_len,nns_import_id,nns_integer_id,nns_content_id,nns_url from nns_vod_media where nns_id='{$item['nns_media_id']}'";
	                $media_info = nl_query_by_db($media_sql, $db);
	                if(is_array($media_info))
	                {
	                    $nns_file_size = $media_info[0]['nns_file_size'];
	                    $nns_file_time_len = $media_info[0]['nns_file_time_len'];
	                    $item['nns_file_len'] = $nns_file_time_len;
	                    $item['nns_file_size'] = $nns_file_size;
	                    
	                    $mg_file_id = $media_info[0]['nns_import_id'];
	                    switch ($sp_config['import_id_mode']) 
		            	{
							case '1':
								$cdn_id = '000000'.$media_info[0]['nns_integer_id'];
								$cdn_id = str_pad($cdn_id,32,"0");
								break;
							case '2':
								$cdn_id = $media_info[0]['nns_import_id'];
								break;
							case '3':
								$cdn_id = CSP_ID . '0000' . $media_info[0]['nns_integer_id'];
								$cdn_id = str_pad($cdn_id,32,"0");
								break;
							case '4':
								$arr_csp_id = explode("|", CSP_ID);
								$str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
								$lest_num = 32-$str_lenth;
								$cdn_id = $arr_csp_id[0].'1'.str_pad($media_info[0]['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
								break;
							default:
								$cdn_id = $item['nns_media_id'];
								break;
		            	}
		            	//根据CP配置确认是否删除CP上的FTP物理文件，需登陆FTP ---begin
		            	if($status==5 && $item['nns_action'] == 'add' && (int)$cp_config['del_cp_file_enabled'] === 1)
		            	{
		            		include_once dirname(dirname(dirname(__FILE__))).'/np/np_ftp.php';
		            		$cp_file_url = $media_info[0]['nns_url'];
		            		$this->__debug($video_info[0]['nns_cp_id'].'删除CP的物理文件'.var_export($cp_file_url,true));
		            		$ftp_passive = (int)$cp_config['down_method_ftp'] ? false : true;
		            		$arr_url = parse_url($cp_file_url);
		            		$ftp = new nns_ftp($arr_url['host'], $arr_url['user'], $arr_url['pass'], $arr_url['port']);
		            		$ftpcon = $ftp->connect(10, $ftp_passive);
		            		if ($ftpcon)
		            		{
		            			$del_file_re = $ftp->delete($arr_url['path']);
		            			$this->__debug($cp_file_url . '删除:'.var_export($del_file_re,true));
		            		}
		            	}
		            	//-----end
	                }
                }
                $mg_asset_type = 3;                
            }
			
			//如果状态是OK最终状态并且消息不为空，则上报给芒果TV    
			$this->__debug(var_export($item,true));
			$flag_message_feedback_enabled = (!isset($sp_config['message_feedback_enabled']) || $sp_config['message_feedback_enabled'] !=1) ? true : false;
            if($status==5 && strlen($item['nns_message_id']) > 0 && $flag_message_feedback_enabled)
            {
//                 include_once dirname(dirname(dirname(__FILE__))).'/np/np_http_curl.class.php';
				include_once dirname(dirname(__FILE__)).'/nn_logic/cp/cp.class.php';
                if(isset($sp_config['message_feedback_mode']) && $sp_config['message_feedback_mode'] == 1)
				{
				// 					$arr_cp_list = nl_cp::query_by_more_id_by_db($db,isset($sp_config['temp_bind_cp_list']) ? $sp_config['temp_bind_cp_list'] : null);
// 					if(isset($arr_cp_list['data_info']) && is_array($arr_cp_list['data_info']))
// 					{
// 						foreach ($arr_cp_list['data_info'] as $arr_cp_val)
// 						{
							$arr_cp_config = null;
// 							if(is_array($arr_cp_val) && !empty($arr_cp_val) && isset($arr_cp_val['nns_config']) && !empty($arr_cp_val['nns_config']))
// 							{
// 								$arr_cp_config = json_decode($arr_cp_val['nns_config'],true);
// 							}
// 							if(is_array($arr_cp_config) && !empty($arr_cp_config))
// 							{
// 								$cdn_id = ($item['nns_type'] == BK_OP_MEDIA && isset($media_info['nns_content_id'])) ? $media_info['nns_content_id'] : '';
								
								$this->message_feedback($cp_config,$item,$cdn_id,$mg_asset_type,$video_info,$mg_asset_id,$mg_part_id,$mg_file_id,$cp_config);
// 							}
// 						}
// 					}
               	}
                else
                {
                    $this->message_feedback($sp_config,$item,$cdn_id,$mg_asset_type,$video_info,$mg_asset_id,$mg_part_id,$mg_file_id,$cp_config);
                }
            }

            /*if(isset($item['nns_message_id']))
            {
                unset($item['nns_message_id']);
            }
            if(isset($item['nns_is_group']))
            {
                unset($item['nns_is_group']);
            }
            if(isset($item['nns_encode_flag']))
            {
                unset($item['nns_encode_flag']);
            }
            if(isset($item['nns_cp_id']))
            {
                unset($item['nns_cp_id']);
            }*/
            //过滤op_log字段
            $arr=array(
                'id'=>$item['nns_id'],
                'type'=> $item['nns_type'],
                'org_id'=>$item['nns_org_id'],
                'create_time'=>$item['nns_create_time'],
                'action'=>$item['nns_action'],
                'status'=>$item['nns_status'],
                'name'=>$item['nns_name'],
                'video_id'=>$item['nns_video_id'],
                'weight'=>$item['nns_weight'],
                'index_id'=>$item['nns_index_id'],
                'media_id'=>$item['nns_media_id'],
                'op_mtime'=>$item['nns_op_mtime'],
                'release_time'=>$item['nns_release_time'],
                'op_id'=>$item['nns_op_id'],
                'category_id'=>$item['nns_category_id'],
                'file_len'=>$item['nns_file_len'],
                'file_size'=>$item['nns_file_size'],
                'id'=>$item['nns_id'],
            );
			$re=nl_db_insert($db,$this->log_table,$arr);
		}
		return $re;
	}

	
	/**
	 * 消息反馈
	 * @param unknown $sp_config
	 * @param unknown $item
	 * @param unknown $cdn_id
	 * @param unknown $mg_asset_type
	 * @param unknown $video_info
	 * @param unknown $mg_asset_id
	 * @param unknown $mg_part_id
	 * @param unknown $mg_file_id
	 * @param unknown $cp_config
	 * @return boolean
	 * @author liangpan
	 * @date 2016-08-26
	 */
	public function message_feedback($sp_config,$item,$cdn_id,$mg_asset_type,$video_info,$mg_asset_id,$mg_part_id,$mg_file_id,$cp_config,$state=1,$str_message='xml import ok')
	{
		include_once dirname(dirname(dirname(__FILE__))).'/np/np_http_curl.class.php';
		if(is_array($sp_config) && !empty($sp_config))
		{
			//查询sp的上报地址/芒果使用站点ID
			if(isset($sp_config['site_id'])&&strlen($sp_config['site_id'])>0&&isset($sp_config['site_callback_url'])&&strlen($sp_config['site_callback_url'])>0)
			{
                //湖南电信添加HW/ZTE标识反馈
                if($item['nns_org_id'] == 'hndx')
                {
                    $cp_id='ZTE';
                }
                else if ($item['nns_org_id'] == 'hndx_hw')
                {
                    $cp_id='HW';
                }
                else
                {
                    $cp_id ='';
                }
				//						$xml='<xmlresult><msgid>'.$item['nns_message_id'].'</msgid><siteid>'.$sp_config['site_id'].'</siteid><state>1</state><msg>xml import ok</msg></xmlresult>';
				$xml_info = array(
						'msgid' => $item['nns_message_id'],
						'state' => $state,
						'msg' => $str_message,
						'info' => array(
								'cdn_id' => $cdn_id,
								'site_id' => $sp_config['site_id'],
								'cp_id' =>$cp_id,
								'mg_asset_type' => $mg_asset_type,
                                'mg_asset_id' => $mg_asset_id,
                                'mg_part_id' => $mg_part_id,
                                'mg_file_id' => $mg_file_id,
						),
				);
				$xml = $this->_build_notify($xml_info);
				$data = array(
						'cmsresult'=>$xml,
				);
				$this->__debug(var_export($sp_config['site_callback_url'],true));
				$this->__debug(var_export($data,true));
		
				$http_curl = new np_http_curl_class();
				for ($i = 0; $i < 3; $i++) {
					//访问媒资注入接口
					$re = $http_curl->post($sp_config['site_callback_url'],$data,null,2);
					//$this->__debug(var_export($sp_config['site_callback_url'],true));
					//$this->__debug(var_export($data,true));
					$curl_info = $http_curl->curl_getinfo();
					$http_code = $curl_info['http_code'];
					$this->__debug('返回状态'.var_export($http_code,true));
					$this->__debug(var_export($curl_info,true));
					$this->__debug(var_export($re,true));
					if ($http_code != 200 && (int)$re === 1) {
						continue;
					} else {
						break;
					}
					 
				}
				//if($http_code==200)
				//{
				//$del_sql = "update nns_mgtvbk_message set nns_message_state=99 where nns_message_id='{$item['nns_message_id']}'";
				//	$sql = "select count(*) as num from nns_mgtvbk_import_op where nns_message_id='{$item['nns_message_id']}'";
				//	$info = nl_query_by_db($sql, $db);
				//	if($info[0]['num']<1)
				//	{
				//		$del_sql = "delete from  nns_mgtvbk_message  where nns_message_id='{$item['nns_message_id']}'";
				//		nl_execute_by_db($del_sql,$db);
				//	}
				//}
			}
			//其他CP反馈,老版本v1
			elseif(isset($sp_config['site_callback_url']) && strlen($sp_config['site_callback_url']) > 0 && file_exists(dirname(dirname(__FILE__)).'/api/'.$item['nns_org_id'].'/'.$item['nns_org_id'].'_sync_source.php'))
			{
				include_once dirname(dirname(__FILE__)).'/api/'.$item['nns_org_id'].'/'.$item['nns_org_id'].'_sync_source.php';
				if(method_exists($item['nns_org_id'].'_sync_source','async_feedback'))
				{
					$class_name = $item['nns_org_id'].'_sync_source';
					$sync_source = new $class_name();
					$sync_source->async_feedback($item,true);
				}
			}
			//其他CP反馈，新版V2
			//elseif (!empty($video_info[0]['nns_cp_id']) && isset($cp_config['site_callback_url']) && strlen($cp_config['site_callback_url']) > 0 && (int)$cp_config['content_feedback_mode'] === 2)
			elseif (!empty($video_info[0]['nns_cp_id']) && (int)$cp_config['content_feedback_mode'] !== 0)
			{
				include_once dirname(dirname(__FILE__)).'/api_v2/common.php';
				$public_execute = new public_execute($video_info[0]['nns_cp_id'],'notify_msg');
				$re_cp = array(
						'msgid' => $item['nns_message_id'],
						'state' => $state,
						'action' => $item['nns_action'] == 'destroy' ? 3 : 1,
						'msg' => $str_message,
						'info' => array(
								'asset_type' => $mg_asset_type,
								'asset_id' => $mg_asset_id,
								'part_id' => $mg_part_id,
								'file_id' => $mg_file_id,
						),
				);
				$this->__debug($video_info[0]['nns_cp_id'].'进行 v2的反馈'.var_export($re_cp,true));
				$public_execute->async_feedback($re_cp,true,false);
			}
		}
		return true;
	}
	
	

	private function __get_order_config($config){

		$order=empty($config['op_task_order'])?'nns_weight desc,nns_release_time desc,nns_video_id asc,nns_op_mtime asc':$config['op_task_order'];
		return $order;
	}

	private function __get_freeze_time_config($config){

		$freeze_time=empty($config['op_task_freeze_time'])?NULL:$config['op_task_freeze_time'];
		return $freeze_time;
	}

	private function __get_config($sp_id){
		$config=sp_model::get_sp_config($sp_id);
		return $config;
	}

	/**
	 * 任务暂停
	 * @param DB
	 * @param 操作指令ID组
	 * @return TRUE 成功
	 * 			FALSE 失败 查看日志错误
	 */

	public function pause($db,$op_ids){
		if (!is_array($op_ids)) return;
		$op_ids=implode("','",$op_ids);
		$op_ids="'".$op_ids."'";
		$sql='update '.$this->table.' set nns_state="1" where nns_id in('.$op_ids.') and nns_status!="'.BK_OP_PROGRESS.'"';

		$re=nl_execute_by_db($sql,$db);
		if($re===FALSE){
    		$this->__error("[pause] DB execute fail \nsql:\n".$sql);
    		return FALSE;
    	}

    	return TRUE;
	}
	/**
	 * 任务恢复
	 * @param DB
	 * @param 操作指令ID组
	 * @return TRUE 成功
	 * 			FALSE 失败 查看日志错误
	 */
	public function resume($db,$op_ids){
		if (!is_array($op_ids)) return;
		$op_ids=implode("','",$op_ids);
		$op_ids="'".$op_ids."'";
		$sql='update '.$this->table.' set nns_state="0" where nns_id in('.$op_ids.') and nns_status!="'.BK_OP_PROGRESS.'"';

		$re=nl_execute_by_db($sql,$db);
		if($re===FALSE){
    		$this->__error("[resume] DB execute fail \nsql:\n".$sql);
    		return FALSE;
    	}

    	return TRUE;
	}

	/**
	 * 获取该分集下是否有片源不为删除状态，并还未执行完毕
	 *  @param DB
	 * @param 分集ID
	 * @param 片源ID
	 * @return int 有 返回一个数量
	 */
	public  function get_index_status($db,$sp_id,$index_id,$media_id){
		$sql="select count(1) as num from ".$this->table." where " .
				"nns_org_id='{$sp_id}' and nns_index_id='{$index_id}' and nns_type='".BK_OP_MEDIA."' " .
				"and nns_action !='".BK_OP_DELETE."' " .
//				如果有相同片源ID的影片在做添加可能会卡住队列，故新增逻辑
				"and nns_media_id!='{$media_id}'";
		//echo $sql;
		$result = nl_query_by_db($sql,$db);

		$result = empty($result[0]['num'])?0:$result[0]['num'];

		return $result;
//		不合理的判断流程，可能会卡住队列，新的流程已改为添加片源的权重默认大于删除片源的操作
//		return 0;
	}

	/**
	 * 审核op数据
	 * @param DB
	 * @param opID
	 * 注意:所有该单位的待审核操作都将被审核
	 */
	public function audit($db,$op_id){
		$lp=np_check_params_policy(array(
			array(
				'value'=>$db,
				'key'=>'db',
				'rule'=>'noempty'
			),
//			array(
//				'value'=>$org_id,
//				'key'=>'org_id',
//				'rule'=>'noempty'
//			),
			array(
				'value'=>$op_id,
				'key'=>'op_id',
				'rule'=>'noempty'
			),
		));

		if ($lp['state']===FALSE){
			$this->__error("[audit] params is wrong \n ".$lp['reason']);
			return $this->__return('102');
		}

		//		准备数据，用于日志转移
		$sql='select * from '.$this->table.
				' where nns_status=\''.BK_OP_UNAUDIT.'\' ' .
				'and nns_id=\''.$op_id.'\' ' ;
//				'and nns_org_id=\''.$org_id.'\' ' .
//				'and nns_'.$type.'_id=\''.$ex_id.'\' ' .
//				'and nns_type=\''.$type.'\'';

		$info=nl_query_by_db($sql,$db);

		if (!is_array($info)){
			$this->__error("[audit] task is not exists \n ".$sql);
			return $this->__return('103');
		}
		
		$updates_sql="select * from ".$this->table.
					" where nns_video_id='{$info[0]['nns_video_id']}' " .
					" and nns_index_id='{$info[0]['nns_index_id']}' " .
					" and nns_media_id='{$info[0]['nns_media_id']}' " .
					" and nns_status='".BK_OP_UNAUDIT."' " .
					" order by nns_op_mtime asc";
					
		$infos=nl_query_by_db($sql,$db);
		
		if (!is_array($infos)){
			$this->__error("[audit] task is not exists \n ".$sql);
			return $this->__return('103');
		}
		
		foreach ($infos as $info){
			
			$update_status='';
			if ($info[0]['nns_type']==BK_OP_MEDIA){
				if ($info[0]['nns_action']==BK_OP_DELETE){
					$update_status=BK_OP_WAIT;
				}else{
					$update_status=BK_OP_WAIT_CLIP;
				}
	
			}else{
				$update_status=BK_OP_WAIT;
				
			}
			
			$sql='update '.$this->table.' set nns_status=\''.$update_status.'\' ' .
					'where nns_status=\''.BK_OP_UNAUDIT.'\' ' .
					'and nns_id="'.$op_id.'" ' ;
			
	//				'and nns_type="'.BK_OP_MEDIA.'" ' .
	//				'and nns_org_id=\''.$org_id.'\' ' .
	//				'and nns_media_id=\''.$media_id.'\' ';
	
			$re=nl_execute_by_db($sql,$db);
			
			if ($re===TRUE){

	//			记录日志 BY S67 2014/2/12
				$this->__add_task_ok_log($db,$infos,$update_status);
	
				$rows=$db->affected_rows();
				if ($rows!==1){
					$this->__error("[audit] execute number is wrong \nnum:".$rows."\nsql:".$sql);
//					return $this->__return('103');
				}
				
			}else{
				$this->__error("[audit] DB execute fail \nsql:\n".$sql);
//				return $this->__return('101');
			}
			
		}
		return $this->__return('100');
		
	}
	
	/**
	 * 根据内容获取OP_ID
	 * @param DB
	 * @param array(
	 * 		"video_id"=>影片ID
	 * 		"index_id"=>分集ID
	 * 		"media_id"=>片源ID
	 * 		"org_id"=>SP ID
	 * 		"type"=>内容类型 
	 * 		"action"=>操作类型
	 * )
	 * @return array()
	 * state 错误码
	 * reason 错误说明
	 * data  数据 若成功为op_id
	 */
	public function get_op_id($db,$params){
		$ex_video_sql=" (nns_video_id='{$params['video_id']}' and nns_type='".BK_OP_VIDEO."')  ";
    	$ex_index_sql=" (nns_video_id='{$params['video_id']}' and nns_index_id='{$params['index_id']}' and  nns_type='".BK_OP_INDEX."') ";
    	$ex_media_sql=" (nns_video_id='{$params['video_id']}' and nns_index_id='{$params['index_id']}' and  nns_media_id='{$params['media_id']}' and nns_type='".BK_OP_MEDIA."') ";

    	$ex_sql="  nns_org_id='{$params['org_id']}' and  ";
    	
    	if ($params['action']==BK_OP_ADD || $params['action']==BK_OP_MODIFY){
    		$action=" (nns_action='".BK_OP_ADD."' or nns_action='".BK_OP_MODIFY."') and ";
    	}else{
    		$action=" nns_action='{$params['action']}'  and ";
    	}
    	
    	switch ($params['type']){
    		case BK_OP_VIDEO:
    			$ex_sql .=$ex_video_sql;
    		break;
    		case BK_OP_INDEX:
    			$ex_sql .= $ex_index_sql;
    		break;
    		case BK_OP_MEDIA:
    			$ex_sql .=$ex_media_sql;
    		break;
    	}

    	$sql="select nns_id from ".$this->table." where ".$ex_sql;

    	$re=nl_query_by_db($sql,$db);
    	
    	if ($re){
			if (is_array($re)){
				return $this->__return('100',$re[0]['nns_id']);
			}elseif ($re===TRUE){
				return $this->__return('103');
			}
		}elseif($re===FALSE){
			$this->__error("[get_op_id] DB execute fail \nsql:\n".$sql);
			return $this->__return('101');
		}
    	
	}
	
	
	/**
	 * 根据内容获取OP_ID
	 * @param DB
	 * @param op_id
	 * @return array()
	 * state 错误码
	 * reason 错误说明
	 * data  数据 若成功为op_id
	 */
	public function wait_op_execute($db,$op_id,$ex_data){
		
		$sql="select * from ".$this->table."  where nns_id='{$op_id}' and nns_status='".BK_OP_WAIT_SP."'";
		
		$info=nl_query_by_db($sql,$db);
		$nns_status = BK_OP_WAIT;
		if(isset($info[0]) && is_array($info[0]))
		{
		    $config = $this->__get_config($info[0]['nns_org_id']);
		    $nns_status = ($info[0]['nns_type']===BK_OP_MEDIA && ($info[0]['nns_action']===BK_OP_ADD || $info[0]['nns_action']===BK_OP_MODIFY) && (int)$config['disabled_clip'] !== 2) ? BK_OP_WAIT_CLIP : BK_OP_WAIT;
		}
		$sql="update ".$this->table." set nns_status='".$nns_status."',nns_ex_data='".$ex_data."' where nns_id='{$op_id}' and nns_status='".BK_OP_WAIT_SP."'";
		
		$re=nl_execute_by_db($sql,$db);
		if ($re===TRUE){	
			$rows=$db->affected_rows();
			if ($rows!==1){
				$this->__error("[wait_op_execute] execute number is wrong \nnum:".$rows."\nsql:".$sql);
			}else{
//			记录日志 BY S67 2014/2/12
				$this->__add_task_ok_log($db,$info,BK_OP_WAIT);
			}
			return $this->__return('100');	
                
		}else{
			$this->__error("[wait_op_execute] DB execute fail \nsql:\n".$sql);
				return $this->__return('101');
		}
		
	}
/****************20150302***************************/
	/**
	 * 手动切片任务
	 * @param $db
	 * @param $org_id  SPID
	 * @param $op_ids  中心指令任务ID
	 * @author zhiyong.luo
	 * @date 2015-03-02
	 */	
	public function get_hand_clip($db,$org_id,$op_ids)
	{
		if(!is_array($op_ids))
		{
			$this->__error("[get_hand_clip] params is wrong \n ".var_export($op_ids,true));
			return $this->__return('102');
		}
		$lp = np_check_params_policy(array(
			array(
				'value'=>$db,
				'key'=>'db',
				'rule'=>'noempty'
			),
			array(
				'value'=>$org_id,
				'key'=>'org_id',
				'rule'=>'noempty'
			),
		));
		if ($lp['state']===FALSE)
		{
			$this->__error("[get_hand_clip] params is wrong \n ".$lp['reason']);
			return $this->__return('102');
		}
		$ids = '';
		foreach ($op_ids as $op_id)
		{
			$ids .= "'" . $op_id . "',"; 
		}
		$ids = rtrim($ids,',');
		//添加切片任务需要去除非等待切片的片源
		$sql = 'select * from '.$this->table.
				' where nns_type="'.BK_OP_MEDIA.'" ' .
				'and nns_status="'.BK_OP_WAIT_CLIP.'" ' .
				'and nns_org_id="'.$org_id.'" ' .
				' and nns_state="0" ' . 
				' and nns_id in (' . $ids . ') and nns_status=2';
		// die($sql);
		$re = nl_query_by_db($sql,$db);

		if ($re===FALSE)
		{
			$this->__error("[get_hand_clip] DB execute fail \nsql:\n".$sql);
			return $this->__return('101');
		}
		elseif ($re === TRUE)
		{
			$re = array();
		}
		return $this->__return('100',$re);
	}
	/**
	 * 组装反馈的XML
	 * @param $params
	 */
	private function _build_notify($params)
	{
		if(!is_array($params) || empty($params))
		{
			return ;
		}
		$dom = new DOMDocument('1.0', 'utf-8');
		$xmlresult = $dom->createElement('xmlresult');
		$dom->appendChild($xmlresult);
		foreach ($params as $key=>$value)
		{
			$$key = $dom->createElement($key);
			$xmlresult->appendchild($$key);
			if(!empty($value) && is_array($value))
			{
				foreach ($value as $k=>$val)
				{							
					$$k = $dom->createElement($k);
					$$key->appendchild($$k);
					//创建元素值
					$content = $dom->createTextNode($val);
					$$k->appendchild($content);
				}	
			}
			else 
			{
				//创建元素值
				$text = $dom->createTextNode($value);
				$$key->appendchild($text);	
			}
		}
		return $dom->saveXML();
	}
}
?>